package com.sky.service.user.impl;

import com.alibaba.fastjson.JSON;
import com.sky.constant.JwtClaimsConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.mapper.user.MerchantMapper;
import com.sky.mapper.user.UserMapper;
import com.sky.pojo.Merchant;
import com.sky.pojo.User;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.result.Result;
import com.sky.service.user.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.utils.MapUtils;
import com.sky.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    private final static String URL = "https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private MerchantMapper merchantMapper;
    @Autowired
    private WeChatProperties weChatProperties;

    @Override
    public UserLoginVO login(UserLoginDTO dto) {
        //去微信获取用户信息，openId
        String openId = getOpenId(dto.getCode());
        log.info("获取到用户openid：{}",openId);
        //判断是否是新用户，通过openId
        User user = userMapper.findByOpenId(openId);
        //如果是新用户，插入一条数据
        if(user == null){
            user = new User();
            user.setOpenid(openId);
            user.setCreateTime(LocalDateTime.now());
            userMapper.insert(user);
        }
        //生成token
        Map<String, Object> map = new HashMap<>();
        map.put(JwtClaimsConstant.USER_ID,user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), map);

        //查询商家信息
        Merchant merchant = merchantMapper.selectById(1l);
        //算价格
        //获取商家位置所在的经纬度
        String merchantLocation = MapUtils.addressToLnglat(merchant.getShopAddress());
        BigDecimal delivoryCost = MapUtils.getDelivoryCost(merchantLocation, dto.getLocation());

        //构建返回值
        UserLoginVO userLoginVO = UserLoginVO.builder()
                .openid(openId)
                .token(token)
                .shopName(merchant.getShopName())
                .shopTelephone(merchant.getShopTelephone())
                .shopId(merchant.getId())
                .shopAddress(merchant.getShopAddress())
                .id(user.getId())
                .deliveryFee(delivoryCost)
                .build();
        return userLoginVO;
    }

    /**
     * 获取微信用户openid
     * @param code
     * @return
     */
    public String getOpenId(String code){
        Map<String, String> param = new HashMap<>();
        param.put("appid", weChatProperties.getAppid());
        param.put("secret",weChatProperties.getSecret());
        param.put("js_code",code);
        param.put("grant_type","authorization_code");
        String response = HttpClientUtil.doGet(URL, param);
        Map map = JSON.parseObject(response, Map.class);
        String openid = (String) map.get("openid");
        return openid;
    }
}
